import React, {Component} from 'react';
import {
    SafeAreaView,
    ScrollView,
    View,
    Image,
    Text,
    StyleSheet,
    RefreshControl,
    Dimensions,
    TouchableOpacity,
    PermissionsAndroid,
} from 'react-native';
import {connect} from 'react-redux';
import {getUserSignExpect} from '../../../api/empActual';
import {Loading} from '../../../utils/Loading';
import {Toast} from '../../../utils/Toast';
import store from '../../../store';
import {getToken} from '../../../utils/Auth';
import AllStyle from '../../../style';
import Icon from 'react-native-vector-icons/AntDesign';
import FontAwesome from 'react-native-vector-icons/FontAwesome';
import EvilIcons from 'react-native-vector-icons/EvilIcons';
import {init, Geolocation} from 'react-native-amap-geolocation';
import {getTimer} from '../../../utils/DateUtils';
import {saveEmpRecords} from '../../../api/empRecords';
import {preventDoubleClick} from '../../../utils/preventDoubleClick';
import {getDistance} from '../../../utils';

//申请权限
PermissionsAndroid.requestMultiple([
    PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
    PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,
]).catch(err => {
    Toast.showWarning(err.toString());
}).then(res => {

});
init({
    ios: '1be169e585123b6e68a91d9aa355ae14',
    android: 'fd68d9ef3201d3ba7376ae6f89673904',
}).then(res => {
    console.log(res, '地图初始化');
}).catch(err => {
    Toast.showWarning(err.toString());
});

const width = Dimensions.get('window').width;
const height = Dimensions.get('window').height;

class signInfoScreen extends Component {
    constructor() {
        super();
        this.state = {
            time: null,
            errorRange: false,
            refreshing: false,
            location: {
                longitude: 0,
                latitude: 0,
            },
            'SignPlaceList': [],
            'empActual': null,
            'EmpRecordsList': [],
            'signGroup': null,
            'empPlanClasses': null,
            'user': {
                'userId': 1,
                'username': 'admin',
                'password': '9ec9750e709431dad22365cabc5c625482e574c74adaebba7dd02f1129e4ce1d',
                'salt': 'YzcmCZNvbXocrsz9dm8e',
                'email': 'root@renren.io',
                'mobile': '13612345678',
                'identityCard': null,
                'status': 1,
                'roleIdList': null,
                'createUserId': 1,
                'createTime': '2016-11-11 11:11:11',
            },
        };
    }

    componentWillUnmount() {
        clearInterval(this.interval);
    }

    goto = (name, params) => {

        const route = {
            name: name,
            params: {
                routePathName: this.props.route.name,
                ...params,
            },

        };
        this.props.navigation.navigate(route);
    };

    //获取现在时间
    tick() {
        this.setState((prevState) => ({
            time: getTimer(new Date()),
        }));
    }

    componentDidMount() {
        this.init();
        this.interval = setInterval(() => this.tick(), 1000);
    }

    componentDidUpdate(prevProps: Readonly<P>, prevState: Readonly<S>, snapshot: SS) {
        if (this.props.route.params != prevProps.route.params) {
            //Loading.hidden()
            this.init();
        }

    }

    //初始化
    init = () => {
        getToken().then(res => {
            if (res != null) {
                //Loading.show();
                getUserSignExpect().then(res => {
                    let {data} = res;
                    let {user, signGroup, empPlanClasses, EmpRecordsList, empActual, SignPlaceList} = data;

                    this.setState({user});
                    this.setState({signGroup});
                    this.setState({EmpRecordsList});
                    this.setState({empActual});
                    if (!SignPlaceList) {
                        SignPlaceList = [];
                    }
                    this.setState({SignPlaceList});
                    this.setState({empPlanClasses});
                    console.log('res------------------------------', res);
                    //获取当前地址
                    let location = this.state.location;

                    Geolocation.getCurrentPosition(({coords}) => {
                        console.log(coords,'coords');
                        let {latitude, longitude} = coords;
                        if (SignPlaceList.length > 0) {
                            for (let [index,item] of SignPlaceList.entries()) {
                                let errorRange = getDistance(item.placeLatitude, item.placeLongitude, latitude.toFixed(6), longitude.toFixed(6));
                                if (errorRange <= item.errorRange) {
                                    this.setState({errorRange: true});
                                    break;
                                }
                                //如果循环到最后一个还没有那说明没有达到范围内
                                if(index===SignPlaceList.length-1){
                                    this.setState({errorRange: false});
                                }
                            }
                        }
                        location.latitude = latitude.toFixed(6);
                        location.longitude = longitude.toFixed(6);
                        this.setState({location});
                    });


                }).catch(err => {
                    Toast.showWarning(err.toString());
                }).finally(() => {
                    //Loading.hidden();
                    setTimeout(() => {
                        this.setState({refreshing: false});
                    }, 500);
                });
            }
        });

    };
    sign = () => {
        if (this.state.errorRange == false) {
            return;
        }
        this.goto('faceRecognitionPunch', {
            recordsLongitude: this.state.location.longitude,
            recordsLatitude: this.state.location.latitude,
        });

        // let data = {
        //     equipment: '待完善.....',
        //     recordsLongitude: this.state.location.longitude,
        //     recordsLatitude: this.state.location.latitude,
        // };
        // Loading.show();
        // saveEmpRecords(data).then(res => {
        //     Loading.hidden();
        //     Toast.showWarning('打卡成功');
        //     this.init();
        // }).catch(err => {
        //     Loading.hidden();
        //     Toast.showWarning(err.toString());
        // }).finally(()=>{
        //     Loading.hidden();
        // });
    };
    onRefresh = () => {
        this.setState({refreshing: true});
        this.init();
    };

    // getDistance(lat1, lon1, lat2, lon2) {
    //     let radLat1 = (lat1 * Math.PI) / 180; //将角度换算为弧度
    //     let radLat2 = (lat2 * Math.PI) / 180; //将角度换算为弧度
    //     let a = radLat1 - radLat2;
    //     let b = (lon1 * Math.PI) / 180 - (lon2 * Math.PI) / 180;
    //     let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(
    //         Math.sin(b / 2), 2)));
    //     s = s * 6378137.0; // 取WGS84标准参考椭球中的地球长半径(单位:m)
    //     //s = Math.round(s * 10000) / 10000; //两点之间距离(保留四位)
    //     return s; //(单位:m)
    // }

    render() {
        return (
            <SafeAreaView style={{flex: 1}}>
                <ScrollView refreshControl={
                    <RefreshControl title={'下拉刷新'} titleColor={'#727981'} refreshing={this.state.refreshing}
                                    onRefresh={this.onRefresh}/>
                }>
                    <View style={style.container}>

                        <View style={style.padding15}>

                            <View style={[AllStyle.card, style.item]}>
                                <View style={style.top_l}>
                                    <View style={style.top_l_logo}>
                                        <FontAwesome color="#999" size={40} name={'user-circle-o'}></FontAwesome>

                                    </View>
                                    <View style={style.top_l_name}>
                                        <Text style={{
                                            fontSize: 18,
                                            fontWeight: '600',
                                            marginBottom: 1,
                                        }}>{this.state.user.username}</Text>
                                        <Text
                                            style={{color: '#798188'}}>{this.state.empPlanClasses != null ? this.state.empPlanClasses.planName : '未加入考勤组'}</Text>
                                    </View>
                                </View>
                                <View style={style.top_r}></View>
                            </View>

                            {
                                this.state.signGroup == null ?
                                    (
                                        <View style={[AllStyle.card, style.body]}>
                                            <View style={style.body_sign}>
                                                <Image
                                                    style={style.body_sign_svg}
                                                    source={require('../../../img/weijiaruGroup.png')}
                                                />
                                                <View style={style.body_sign_text}>
                                                    <Text style={{
                                                        fontSize: 14,
                                                        color: '#798189',
                                                        marginLeft: 10,
                                                    }}>未加入考勤组,无需打卡</Text>
                                                </View>
                                            </View>
                                        </View>
                                    ) : (
                                        <View style={[AllStyle.card, style.body]}>
                                            {
                                                this.state.empActual == null ? (
                                                    <View style={style.body_sign_text}>
                                                        <Text style={{
                                                            fontSize: 14,
                                                            color: '#798189',
                                                            marginLeft: 10,
                                                        }}>今日未排班,休息。</Text>
                                                    </View>) : (
                                                    <View style={style.body_top}>
                                                        <View style={style.body_top_time}>
                                                            <Text
                                                                style={style.body_top_time_text}>上班{this.state.empActual.expectWorkTime.substring(11, 16)}</Text>
                                                            <Text
                                                                style={style.body_top_time_desc}>{this.state.EmpRecordsList[0] != null ? this.state.EmpRecordsList[0].recordsDateTime.substring(11, 16) + '已打卡' : '未打卡'}</Text>
                                                        </View>
                                                        <View style={style.body_top_time}>
                                                            <Text
                                                                style={style.body_top_time_text}>下班{this.state.empActual.expectOffworkTime.substring(11, 16)}</Text>
                                                            <Text
                                                                style={style.body_top_time_desc}>{this.state.EmpRecordsList.length > 1 ? this.state.EmpRecordsList[this.state.EmpRecordsList.length - 1].recordsDateTime.substring(11, 16) + '已打卡' : '未打卡'}</Text>
                                                        </View>
                                                    </View>
                                                )
                                            }

                                            <View style={style.body_sign}>
                                                <TouchableOpacity onPress={() => {
                                                    preventDoubleClick(this.sign, 15000);
                                                }}>
                                                    <View
                                                        style={[style.body_sign_btn, {backgroundColor: this.state.errorRange == true ? '#009DFE' : '#F56C6C'}]}>
                                                        <View style={style.body_sign_ne_btn}>


                                                            <Text style={{
                                                                color: '#685C44',
                                                                fontSize: 22,
                                                                fontWeight: 'bold',
                                                            }}>{this.state.errorRange == true ? '打卡' : '超出范围'}

                                                            </Text>
                                                            <Text style={{
                                                                color: this.state.errorRange == true ? '#685C44' : '#685C44',
                                                                fontSize: 17,
                                                                fontWeight: 'bold',
                                                            }}>{this.state.time}</Text>
                                                        </View>
                                                    </View>
                                                </TouchableOpacity>


                                                {this.state.SignPlaceList.map((item, i) => {
                                                    return (
                                                        <View key={i} style={style.body_sign_text}>
                                                            <EvilIcons size={15} name={'location'}
                                                                       style={{color: '#798189'}}></EvilIcons>
                                                            <Text
                                                                style={{
                                                                    fontSize: 14,
                                                                    color: '#798189',
                                                                    marginLeft: 5,
                                                                }}>{item.signPosition}</Text>
                                                        </View>
                                                    );
                                                })}
                                                {this.state.errorRange == true ? (
                                                        <View style={style.body_sign_text}>
                                                            <Icon size={14} name={'checkcircle'}
                                                                  style={{color: '#00B852'}}></Icon>
                                                            <Text
                                                                style={{
                                                                    fontSize: 14,
                                                                    color: '#798189',
                                                                    marginLeft: 10,
                                                                }}>已经进入考勤范围</Text>
                                                        </View>
                                                    ) :
                                                    (<View style={style.body_sign_text}>
                                                        <Icon size={14} name={'closecircle'}
                                                              style={{color: '#f56c6c'}}></Icon>
                                                        <Text
                                                            style={{
                                                                fontSize: 14,
                                                                color: '#F56C6C',
                                                                marginLeft: 10,
                                                            }}>温馨提示：不在考勤范围内！</Text>

                                                    </View>)
                                                }
                                                {
                                                    this.state.errorRange==false&&

                                                <TouchableOpacity onPress={
                                                ()=>{
                                                    this.goto('locationListScreen',{title:'考勤打卡地点',locations:this.state.SignPlaceList})
                                                }
                                                } >
                                                    <View>
                                                        <Text
                                                            style={{
                                                                fontSize: 14,
                                                                color: '#F56C6C',
                                                                marginLeft: 10,
                                                            }}
                                                        >点击查看考勤点</Text>
                                                    </View>
                                                </TouchableOpacity> }

                                            </View>
                                        </View>
                                    )

                            }


                        </View>

                    </View>
                </ScrollView>
            </SafeAreaView>
        );
    }

};
const style = StyleSheet.create({
    container: {
        backgroundColor: '#F1F2F6',
        flex: 1,
        alignItems: 'center',
        marginTop: 15,
    },
    item: {
        width: width - 30,
        flexDirection: 'row',
        justifyContent: 'space-between',
        padding: 15,
    },
    top_l: {
        flexDirection: 'row',
        justifyContent: 'space-between',
    },
    top_l_logo: {
        justifyContent: 'center',
        alignItems: 'center',
        //backgroundColor: '#409EFF',
        borderRadius: 5,
        marginRight: 15,
        width: 45,
        height: 45,

    },
    top_l_name: {
        justifyContent: 'center',
        // alignItems: 'center',
    },
    top_r: {},
    body: {
        //height:height-280,
        width: width - 30,
        padding: 15,
    },
    body_top: {
        flexDirection: 'row',
        justifyContent: 'space-between',
    },
    body_top_time: {
        borderRadius: 6,
        backgroundColor: '#ECECED',
        padding: 10,
        justifyContent: 'space-between',
        width: width / 2 - 15 - 15 - 5,
    },
    body_top_time_text: {
        color: '#111E2C',
        fontSize: 17,
        marginBottom: 5,
    },
    body_top_time_desc: {
        color: '#727981',
    },
    body_sign: {
        // backgroundColor:'red',
        height: height - 280 - 100,
        justifyContent: 'center',
        alignItems: 'center',
    },
    body_sign_btn: {
        alignItems: 'center',
        justifyContent: 'center',
        borderRadius: 70,
        width: 140,
        height: 140,

    },
    body_sign_ne_btn: {
        backgroundColor: '#fff',
        alignItems: 'center',
        justifyContent: 'center',
        borderRadius: 60,
        width: 120,
        height: 120,
    },
    body_sign_text: {
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        marginTop: 20,
    },
    body_sign_svg: {
        width: 200,
        height: 200,
    },
});


export default connect(null, null)(signInfoScreen);
